import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

// 导入页面组件
import Index from '@/pages/Index'
import List from '@/pages/List'
import Show from '@/pages/Show'
import Login from '@/pages/Login'
import Reg from '@/pages/Reg'
import Add from '@/pages/Add'
import User from '@/pages/User'
import Cate from '@/pages/Cate'
import Layout from '@/pages/Layout'
import UserSc from '@/pages/User/Sc'
import UserArticle from '@/pages/User/Article'
import UserZan from '@/pages/User/Zan'
import UserEdit from '@/pages/User/Edit'
import store from '@/store'


let router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/index',
      children: [
        {
          path: '/index',
          component: Index
        },
        {
          path: '/add',
          component: Add
        },
        {
          path: '/cate',
          component: Cate
        },
        {
          path: '/user',
          component: User,
        },
      ]
    },
    {
      path: '/user/sc',
      component: UserSc,
      meta: { needLogin: true }
    },
    {
      path: '/user/zan',
      component: UserZan,
      meta: { needLogin: true }
    },
    {
      path: '/user/article',
      component: UserArticle,
      meta: { needLogin: true }
    },
    {
      path: '/user/edit',
      component: UserEdit
    },
    {
      path: '/list/:id?',
      component: List
    },
    {
      path: '/show/:id?',
      component: Show
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/reg',
      component: Reg
    },

  ]
})
const whiteList = ['/login', '/reg']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router